package com.ruoyi.web.controller.system;

import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.config.MiniProConfig;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysMenu;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.entity.WxUser;
import com.ruoyi.common.core.domain.model.LoginBody;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.framework.web.service.SysLoginService;
import com.ruoyi.framework.web.service.SysPermissionService;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.system.service.ISysMenuService;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.system.service.IWxUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.utils.aes.AesEncryptUtil;
import com.ruoyi.common.utils.aes.EncryptedString;

import javax.servlet.http.HttpServletRequest;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * 登录验证
 *
 * @author ruoyi
 */
@RestController
public class SysLoginController {
    @Autowired
    private SysLoginService loginService;

    @Autowired
    private ISysMenuService menuService;

    @Autowired
    private SysPermissionService permissionService;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private MiniProConfig miniProConfig;

    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private IWxUserService wxUserService;

    /**
     * 登录方法
     *
     * @param loginBody 登录信息
     * @return 结果
     */
    @PostMapping("/login")
    public AjaxResult login(@RequestBody LoginBody loginBody) {
        /*AjaxResult ajax = AjaxResult.success();
        String userName = "";
        String password = "";
        try {
            userName = AesEncryptUtil.desEncryptForJS(loginBody.getUsername(), EncryptedString.jskey);
            password = AesEncryptUtil.desEncryptForJS(loginBody.getPassword(), EncryptedString.jskey);
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 生成令牌
        String token = loginService.login(userName, password, loginBody.getCode(),
                loginBody.getUuid());
        ajax.put(Constants.TOKEN, token);
        return ajax;*/
        AjaxResult ajax = AjaxResult.success();
        // 生成令牌
        String token = loginService.login(loginBody.getUsername(), loginBody.getPassword(), loginBody.getCode(),
                loginBody.getUuid());
        ajax.put(Constants.TOKEN, token);
        return ajax;
    }

    /**
     * 获取用户信息
     *
     * @return 用户信息
     */
    @GetMapping("getInfo")
    public AjaxResult getInfo() {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        // 角色集合
        Set<String> roles = permissionService.getRolePermission(user);
        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(user);
        AjaxResult ajax = AjaxResult.success();
        ajax.put("user", user);
        ajax.put("roles", roles);
        ajax.put("permissions", permissions);
        return ajax;
    }

    /**
     * 获取路由信息
     *
     * @return 路由信息
     */
    @GetMapping("getRouters")
    public AjaxResult getRouters() {
        String userId = SecurityUtils.getUserId();
        List<SysMenu> menus = menuService.selectMenuTreeByUserId(userId);
        return AjaxResult.success(menuService.buildMenus(menus));
    }



    /**
     * 小程序登录方法
     * @param code 登录信息
     * @return 结果
     */
    @GetMapping(value = "/wxLogin")
    public AjaxResult wxLogin(@RequestParam(name="code",required=true) String code, HttpServletRequest request){
        AjaxResult ajax = AjaxResult.success();

        //token无效时，重新获取token
        //登录凭证不能为空
        if (StringUtils.isBlank(code)) {
            return AjaxResult.error("code 不能为空");
        }
        //小程序唯一标识   (在微信小程序管理后台获取)
        String wxspAppid = miniProConfig.getAppId();
        //小程序的 app secret (在微信小程序管理后台获取)
        String wxspSecret = miniProConfig.getSecret();
        //授权（必填）
        String grantType = miniProConfig.getGrantType();

        //////////////// 1、向微信服务器 使用登录凭证 code 获取 session_key 和 openid ////////////////
//		https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code
        //请求参数
        String params = "appid=" + wxspAppid + "&secret=" + wxspSecret + "&js_code=" + code + "&grant_type=" + grantType;
        //发送请求
        String sr = HttpUtils.sendGet("https://api.weixin.qq.com/sns/jscode2session", params);
        //解析相应内容（转换成json对象）
        JSONObject json = JSONObject.parseObject(sr);
        if(json == null || json.get("openid") == null){
            return AjaxResult.error("请求失败！");
        }
        String openId = (String) json.get("openid");

        Set<String> perms = new HashSet<String>();
        // 生成令牌
        String token = loginService.wxLogin(openId, openId);
        //查询一下此openId是否已经有token了，有的话就直接返回
        WxUser wxUser = wxUserService.selectWxUserByOpenId(openId);
        if(wxUser != null){
            ajax.put("wxUser", wxUser);
            if(wxUser.getUserId() != null){
                //获取sysUser数据
                SysUser sysUser = sysUserService.selectUserById(wxUser.getUserId());
                if(sysUser != null){
                    //更新登录时间
                    sysUser.setLoginDate(DateUtils.getNowDate());
                    sysUserService.updateUserById(sysUser);

                    ajax.put("sysUser", sysUser);
                    // 管理员拥有所有权限
                    if (sysUser.isAdmin()) {
                        perms.add("*:*:*");
                    } else {
                        perms.addAll(menuService.selectMenuPermsByUserId(wxUser.getUserId()));
                    }
                }else{
                    wxUser.setUserId(null);
                    wxUserService.unBindWxUser(wxUser.getId());
                }
            }
        }

        ajax.put("permissions", perms);
//        System.out.println(perms);

        ajax.put(Constants.TOKEN, token);
        return ajax;
    }

}
